package com.glory.brepda.activity.material;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

public class MaterialFlowTestingIqcActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llMain)
    LinearLayout llMain;

    // 物料批次输入框
    private FreeUI_ClearEditText etMLotID;

    // 物料名
    private TextView tvMaterialName;

    // 物料描述
    private TextView tvMaterialDesc;

    // 推力数据
    private LinearLayout llThrust;
    private FreeUI_ClearEditText etThrust;
    private ImageView ivThrustIsPass;

    // 空洞数据
    private LinearLayout llHollow;
    private FreeUI_ClearEditText etHollow;
    private ImageView ivHollowIsPass;

    // 拉力数据
    private LinearLayout llPull;
    private FreeUI_ClearEditText etPull;
    private ImageView ivPullIsPass;

    private Map<Integer, String> iqcResultMap;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_material_flow_testing_iqc;
    }

    @Override
    protected void initView() {

        etMLotID = findViewById(R.id.etMLotID);
        tvMaterialName = findViewById(R.id.tvMaterialName);
        tvMaterialDesc = findViewById(R.id.tvMaterialDesc);
        llThrust = findViewById(R.id.llThrust);
        etThrust = findViewById(R.id.etThrust);
        ivThrustIsPass = findViewById(R.id.ivThrustIsPass);

        llHollow = findViewById(R.id.llHollow);
        etHollow = findViewById(R.id.etHollow);
        ivHollowIsPass = findViewById(R.id.ivHollowIsPass);

        llPull = findViewById(R.id.llPull);
        etPull = findViewById(R.id.etPull);
        ivPullIsPass = findViewById(R.id.ivPullIsPass);

        setMainLayout(llMain);
        tvTitle.setText(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY));

        // 输入物料批次号后，根据物料批次号解析相关信息
        initEdit(etMLotID, this::parseMaterialMessage);

    }

    /**
     * 发送物料批次号到后台接口检索物料批次号信息
     * @param mLotID 扫描的物料批次号
     */
    private void parseMaterialMessage(String mLotID) {

        if (StringUtils.isEmpty(mLotID)) {
            return;
        }

        FreeUI_EntityCallBack<BaseResponseBean<JsonObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JsonObject>>
                (new TypeToken<BaseResponseBean<JsonObject>>() {
                }.getType(),getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JsonObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(MaterialFlowTestingIqcActivity.this, true, getSupportFragmentManager())) {
                    try {
                        JsonObject mLot = response.body().getResponse().getBody().get("XMLot").getAsJsonObject();

                        // 这里不去检查是否有空指针异常，因为正常都会报错出来被下面的逻辑捕捉到，进而执行提示让开发人员去检查
                        tvMaterialName.setText(Objects.toString(mLot.get("MATERIALNAME").getAsString(), StringUtils.EMPTY));
                        tvMaterialDesc.setText(Objects.toString(mLot.get("MATERIALDESC").getAsString(), StringUtils.EMPTY));
                        // 根据物料类型去显示要输入的测试数据以及结果
                        showDataInputBox(Objects.toString(mLot.get("MATERIALTYPE").getAsString(), StringUtils.EMPTY));

                    } catch (Exception e) {
                        // PDA记录错误信息
                        super.onError(response);
                        FreeApi_LogUtils.saveErrorMessages(e, "getAndSetMLotMessage");
                        showToast("获取物料批信息异常，请联系管理员", false);
                        // 清空掉，物料描述里面的信息
                        MyUtils.clearTextInTextView(tvMaterialDesc, tvMaterialName);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JsonObject>> response) {
                super.onError(response);
                FreeApi_LogUtils.saveErrorMessages(response.getException(), "getAndSetMLotMessage");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTION_TYPE", "QUERY_MLOT");

        HashMap<String, Object> materialMap = new HashMap<>(1, 1);
        materialMap.put("MLOTID", mLotID);

        map.add("MLOT", new JsonParser().parse(new Gson().toJson(materialMap)).getAsJsonObject());
        NetUtils.requestPostNet("IF.MLOTFLOWTESTING", "Common", MaterialFlowTestingIqcActivity.this, map, callBack);
    }

    /**
     * 根据物料类型去显示要提交的测试权限，物料类型判断引用mes系统里面记录的物料类型，因为怕它胶水是用的支的，必须要通过mes系统查询才知道是什么物料类型
     * @param materialType 物料类型，目前支持：內引线：In_The_Lead；胶水：Silver_Glue、Insulated；（助焊剂、焊料、锡膏）：Solder、Solder_Paste
     */
    private void showDataInputBox(String materialType) {

        if (StringUtils.isEmpty(materialType)) {
            showToast("未能正确识别该物料物料类型，请联系管理员", false);
            llHollow.setVisibility(View.GONE);
            llThrust.setVisibility(View.GONE);
            llPull.setVisibility(View.GONE);
            return;
        }

        // 将显示是否合格的图标隐藏掉
        ivHollowIsPass.setVisibility(View.GONE);
        ivThrustIsPass.setVisibility(View.GONE);
        ivPullIsPass.setVisibility(View.GONE);

        // 內引线
        if (StringUtils.equals(materialType, "In_The_Lead")) {
            // 內引线 显示拉力数据输入框
            llPull.setVisibility(View.VISIBLE);
            etPull.setVisibility(View.VISIBLE);

            llHollow.setVisibility(View.GONE);
            llThrust.setVisibility(View.GONE);
        } else if (StringUtils.equals(materialType, "Silver_Glue")
             || StringUtils.equals(materialType, "Insulated")) { // 胶水
            // 胶水 显示 芯片推力数据
            llPull.setVisibility(View.GONE);
            llHollow.setVisibility(View.GONE);

            llThrust.setVisibility(View.VISIBLE);
            etThrust.setVisibility(View.VISIBLE);
        } else if (StringUtils.equals(materialType, "Solder")
            || StringUtils.equals(materialType, "Solder_Paste")) {
            // 助焊剂、焊料、锡膏 显示 芯片推力、芯片空洞数据输入框
            llPull.setVisibility(View.GONE);
            llHollow.setVisibility(View.VISIBLE);
            etHollow.setVisibility(View.VISIBLE);

            llThrust.setVisibility(View.VISIBLE);
            etThrust.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.tvBaseSubmit, R.id.ivPullShow, R.id.ivHollowShow, R.id.ivThrustShow})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tvBaseSubmit) {
            // 显示确定按钮，点击确定后提交试流物料检验信息
            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", this::submitFlowTestingResult, ()->{}).show(getSupportFragmentManager(),"MaterialFlowTestingIqc");
        } else if (view.getId() == R.id.ivPullShow) {
            // 显示拉力数据输入框
            showFlowTestingResultDialog("pull", true, etPull, ivPullIsPass);
        } else if (view.getId() == R.id.ivHollowShow) {
            // 显示空洞数据输入框
            showFlowTestingResultDialog("hollow", false, etHollow, ivHollowIsPass);
        } else if (view.getId() == R.id.ivThrustShow) {
            // 显示推力数据输入框
            showFlowTestingResultDialog("thrust", true, etThrust, ivThrustIsPass);
        }
    }

    /**
     * 根据用户点击的检测数据编辑框，显示副页面给用户输入检测数据，输入完成之后将数据回显到主页面上
     * @param dataType 输入框类型，主要用来确定副显示框的标题
     * @param isNormalInput 是否普通输入框，目前有普通和特殊两种输入框，普通：__；特殊：__/__，需要输入两个数据
     * @param callBackEditText 主页面的检测数据输入框，可以用来回显检测数据，并根据其id存储检验结果到字典里面
     * @param callBackImageView 主页面的合格或不合格显示（以图片方式呈现），合格显示打勾图片，不合格显示打叉图片
     */
    private void showFlowTestingResultDialog(String dataType, boolean isNormalInput
            , FreeUI_ClearEditText callBackEditText, ImageView callBackImageView) {

        if (MyUtils.checkTextIsEmptyInAnyTextView(false, etMLotID, tvMaterialDesc)) {
            showToast("信息填写未完成，请检查", false);
            return;
        }

        // 确定副显示框标题
        String dataInputTitle;

        if (StringUtils.equals("pull", dataType)) {
            dataInputTitle = "压焊拉力";
        } else if (StringUtils.equals("hollow", dataType)) {
            dataInputTitle = "粘片空洞";
        } else {
            dataInputTitle = "粘片推力";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(MaterialFlowTestingIqcActivity.this)
            .setNegativeButton("取消", (DialogInterface dialogInterface, int i) -> {});
        View view = LayoutInflater.from(MaterialFlowTestingIqcActivity.this).inflate(R.layout.mlot_iqc_data_input, null);

        // 设置标题
        TextView title = view.findViewById(R.id.tvTitle);
        title.setText(dataInputTitle);

        // 隐藏掉提交按钮，页面按确定和取消来确定是否提交信息到后台
        view.findViewById(R.id.tvBaseSubmit).setVisibility(View.GONE);

        // 检验是否合格按钮
        RadioButton rbPass = view.findViewById(R.id.rbPass);
        RadioButton rbNotPass = view.findViewById(R.id.rbNotPass);

        // 数据集合框
        RecyclerView rvList = view.findViewById(R.id.rvList);
        initRecyclerView(rvList, this);
        MLotFlowTestingIqcDataAdapter mLotFlowTestingIqcDataAdapter = new MLotFlowTestingIqcDataAdapter(null);
        mLotFlowTestingIqcDataAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mLotFlowTestingIqcDataAdapter.isFirstOnly(true);
        rvList.setAdapter(mLotFlowTestingIqcDataAdapter);

        // ========== 主页面的数据显示到这个页面上 ==========
        if (StringUtils.isNotEmpty(getText(callBackEditText))) {
            mLotFlowTestingIqcDataAdapter.addData(0
                    , Arrays.asList(StringUtils.split(getText(callBackEditText), ";")));
        }

        // 回显是否合格到单选框上面，具体值在字典里iqcResultMap根据编辑框的id能够获取到
        if (iqcResultMap != null && iqcResultMap.get(callBackEditText.getId()) != null) {
            if (StringUtils.equals("Y", iqcResultMap.get(callBackEditText.getId()))) {
                rbPass.setChecked(true);
            } else {
                rbNotPass.setChecked(true);
            }
        }
        // ========== 主页面的数据显示到这个页面上结束 ==========


        // ========== 区分是普通的输入框，还是特殊的输入框。并注册输入框编辑事件 ==========
        if (isNormalInput) {

            // 普通数据输入框：粘片推力，压焊拉力
            FreeUI_ClearEditText etNormalInput = view.findViewById(R.id.etNormalInput);
            // 编辑数据的时候直接添加
            initEdit(etNormalInput, s -> {
                if (StringUtils.isEmpty(s)) {
                    return;
                }
                mLotFlowTestingIqcDataAdapter.addData(s);
                MyUtils.clearTextInTextView(etNormalInput);
                new Handler().postDelayed(etNormalInput::requestFocus, 500);
            });

        } else {
            // 隐藏掉普通数据输入框
            view.findViewById(R.id.llNormalInput).setVisibility(View.GONE);
            // 显示特殊输入框
            view.findViewById(R.id.llSpecialInput).setVisibility(View.VISIBLE);

            // 特殊输入框1
            FreeUI_ClearEditText etSpecialInput1 = view.findViewById(R.id.etSpecialInput1);

            // 特殊输入框2
            FreeUI_ClearEditText etSpecialInput2 = view.findViewById(R.id.etSpecialInput2);

            // 注册两个特殊编辑框编辑事件
            initEdit(etSpecialInput1, s -> addSpecialData(etSpecialInput1, etSpecialInput2, mLotFlowTestingIqcDataAdapter, etSpecialInput2));

            initEdit(etSpecialInput2, s -> addSpecialData(etSpecialInput1, etSpecialInput2, mLotFlowTestingIqcDataAdapter, etSpecialInput1));


        }
        // ========== 区分是普通的输入框，还是特殊的输入框。并注册输入框编辑事件结束 ==========

        // ========== 点击确定之后将数据回显到主页面上 ==========
        builder.setPositiveButton("确定", (DialogInterface dialogInterface, int i) -> {
            // 回显相关数据
            if (mLotFlowTestingIqcDataAdapter.getData().size() == 0 ) {
                callBackEditText.setText(StringUtils.EMPTY);
                callBackImageView.setVisibility(View.GONE);
                return;
            }

            final StringBuilder callBackDataBuilder = new StringBuilder();
            for (String tempData:
                    mLotFlowTestingIqcDataAdapter.getData()) {
                callBackDataBuilder.append(tempData).append(";");
            }

            // 将数据回显到主页面上
            callBackEditText.setText(callBackDataBuilder.toString());

            // 回显是否合格
            // 显示合格图片（打勾）或 不合格图片（打叉）
            callBackImageView.setImageResource(rbPass.isChecked() ? R.drawable.sure : R.drawable.del);
            if (iqcResultMap == null) {
                iqcResultMap = new HashMap<>(3, 1);
            }
            iqcResultMap.put(callBackEditText.getId(), rbPass.isChecked() ? "Y" : "N");

            // 显示相关数据是否合格
            callBackImageView.setVisibility(View.VISIBLE);

        });
        // ========== 点击确定之后将数据回显到主页面上结束 ==========

        builder.setView(view);

        builder.setCancelable(true);

        // 显示输入框
        builder.show();
    }

    /**
     * 特殊输入框，添加数据到集合里面，由于它是要输入两个数据才触发一次添加数据，故写了一个方法集成一下
     * @param specialInput1EditText 特殊输入框1
     * @param specialInput2EditText 特殊输入框2
     * @param adapter 数据集合，用来添加数据
     * @param requestFocusView 添加完数据之后，输入框获取焦点
     */
    private void addSpecialData(FreeUI_ClearEditText specialInput1EditText, FreeUI_ClearEditText specialInput2EditText, BaseQuickAdapter<String, BaseViewHolder> adapter
            ,View requestFocusView) {

        // 先聚焦到另外一个输入框，后执行检查卡是否满足添加数据到adapter条件
        new Handler().postDelayed(requestFocusView::requestFocus, 300);

        if (StringUtils.isAnyEmpty(getText(specialInput1EditText), getText(specialInput2EditText))) {
            return;
        }

        adapter.addData(getText(specialInput1EditText) + "/" + getText(specialInput2EditText));

        MyUtils.clearTextInTextView(specialInput1EditText, specialInput2EditText);

    }


    /**
     * 提交试流检验结果
     */
    private void submitFlowTestingResult() {
        // 检查是否有填写信息缺失
        if (MyUtils.checkTextIsEmptyInAnyTextView(true, etMLotID, tvMaterialDesc, tvMaterialName
                ,etHollow, etPull, etThrust)) {
            showToast("信息填写未完成，请检查", false);
            return;
        }


        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("提交成功",true);
                    // 成功之后清除掉相关信息
                    cleanTextWhileSuccess();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "submitFlowTestingResult");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTION_TYPE", "FLOW_TESTING_IQC");

        HashMap<String, Object> materialMap = new HashMap<>(1,1);
        materialMap.put("MLOTID", getText(etMLotID));

        map.add("MLOT", new JsonParser().parse(new Gson().toJson(materialMap)).getAsJsonObject());
        map.add("MLOTIQCLIST", new JsonParser()
                .parse(new Gson().toJson(parseMLotIqcData(etPull, etThrust, etHollow)))
                .getAsJsonArray());
        NetUtils.requestPostNet("IF.MLOTFLOWTESTING", "Common", MaterialFlowTestingIqcActivity.this, map, callback);

    }

    /**
     * 根据显示的输入框的数据，以及相应的检测结果iqcResultMap（根据viewId来获取结果），来生成json数据生成结果例子：
     * "MLOTIQCLIST": [
     *    {
     *        "JUDGERESULT": "Y",
     *        "COMMENTS": "压焊拉力数据",
     *        "MLOTIQCDETAIL": [
     *            {
     *                "ACTIONCOMMENT": "123;456;888;999"
     *            }
     *        ]
     *    },
     *    {
     *          "JUDGERESULT": "Y",
     *          "COMMENTS": "粘片推力数据",
     *          "MLOTIQCDETAIL": [
     *              {
     *                  "ACTIONCOMMENT": "123;456;888;999"
     *              }
     *          ]
     *     }
     * ]
     * @param textViewList 输入显示框
     * @return List<JsonObject>，每个输入框对应一个jsonObject，
     */
    private List<JsonObject> parseMLotIqcData(final TextView... textViewList) {

        ArrayList<JsonObject> iqcDataList;

        if (textViewList.length == 0) {
            return null;
        }

        iqcDataList = new ArrayList<>(textViewList.length);

        for (TextView textView : textViewList) {

            // 文本输入框内没有内容的，肯定是不会有检验结果的，这里选文本框判断就好
            if (textView.getVisibility() == View.VISIBLE && StringUtils.isNotEmpty(textView.getText())) {
                JsonObject map = new JsonObject();
                // 生成检验项目名及对应检验结果JSON
                map.addProperty("JUDGERESULT", iqcResultMap.get(textView.getId()));
                map.addProperty("COMMENTS", String.valueOf(textView.getHint()));

                // 生成检验项对应检测结果
                // 后台的 iqcDetail是用集合List来接收的，故这里需要定义一个集合List来造json出来
                List<HashMap<String, Object>> iqcDetailMapList = new ArrayList<>(1);
                HashMap<String, Object> iqcDetailMap = new HashMap<>(1, 1);
                iqcDetailMap.put("ACTIONCOMMENT", String.valueOf(textView.getText()));
                iqcDetailMapList.add(iqcDetailMap);
                map.add("MLOTIQCDETAIL", new JsonParser().parse(new Gson().toJson(iqcDetailMapList)).getAsJsonArray());
                iqcDataList.add(map);
            }
        }

        // 循环检查没有组件有空值的，返回false
        return iqcDataList;


    }


    @Override
    protected void initData() {

    }

    /**
     * 完成业务后，清除掉输入框，文本框里面的信息
     */
    private void cleanTextWhileSuccess() {
        MyUtils.clearTextInTextView(etMLotID ,tvMaterialName, tvMaterialDesc, etHollow, etThrust, etPull);
    }

}

/**
 * 校验测试数据添加 适配器
 */
class MLotFlowTestingIqcDataAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

    public MLotFlowTestingIqcDataAdapter(@Nullable List<String> data) {
        super(R.layout.adapter_lot_shelves, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, String s) {
        helper.setGone(R.id.tvCircuit,false);
        helper.setText(R.id.tvLot,String.valueOf(helper.getAdapterPosition() + 1));
        helper.setText(R.id.tvLineID,s);

        helper.getView(R.id.ivDelete).setOnClickListener(view -> {
            remove(helper.getAdapterPosition());
        });
    }

}